Encoding.default_external = Encoding.find('utf-8')
require 'sinatra'
$LOAD_PATH << File.dirname(__FILE__)+"/lib"
require 'document'

set :title => "基于Sinatra框架的Kendo文档展示" #,:menus=>{}
set :markdown,:layout_engine=>:erb
set :public_folder => File.dirname(__FILE__)+'/assets'

configure do
  Document.load(File.dirname(__FILE__)+"/views/documents")
end
# error 400..510 do
#   'Boom'
# end
# error do
#   'Sorry there was a nasty error - ' + env['sinatra.error'].message
# end

helpers do

  def init_menu 
    menus ||={}
    if !Document.documents.nil?
      for doc in Document.documents
        menus[doc[0]]=doc[1]
        #:menus.push(doc.rel_path)
        #menus.store(doc[0],doc[1])
      end
    end
    return menus
  end

end

get '/' do 
  #File.dirname(__FILE__)
  markdown :index,:locals => {:title=>settings.title}
end

get '/docs/*' do |path|
  @config = {}
  #document=Document.new("#{File.dirname(__FILE__)}/views/documents/#{path}.md")
  if path.nil? || path==''
    path="introduction"
  end
  document=Document["#{path.split('/').last}"]
  pass unless document
  erb :"pages/document",:locals => document.to_hash.merge({list:init_menu()})
  #params['splat']
  #document= Document.get('kendo')
  #document=Document.documents.select { |k,v| k.end_with?("#{path}.md") }
  #"#{document[0]}"
  #pass unless document
  #erb :"pages/document",:locals => {:title=>settings.title,:documents=>Document.documents,}
end

get '/archives' do
  erb :"pages/archives",:locals=>{:title=>settings.title,:list=>init_menu()}
end

get '/kendo-ui/introduction' do
  redirect to('/docs/introduction')
end

# get '/api/javascript/*' do
#   File.dirname(File.dirname(__FILE__)+"/views"+request.path_info)
  # mdwyp=MarkdownWithYamlProcess.new
  # content=mdwyp.body(File.dirname(__FILE__)+"/views"+request.path_info)
  # markdown content,:locals => {:title=>settings.title}
  #request.path_info
  #txt=File.new(File.dirname(__FILE__)+'/views/'+request.path_info+'.md').lines.take_while{ |line| (!line.strip.empty?)}
  #txt
  #markdown :"#{request.path_info}",:locals => {:title=>settings.title}
#end
